import * as FileSaver from 'file-saver';
import { PREVIEW_TYPE } from './constant';

export const getFileType = (name = '') =>
    name
        .split('.')
        .pop()
        .toLowerCase();

export const checkFileSize = (file, maxSize = 0) => {
    const size = (file?.size || 0) / 1024 / 1024;
    return size <= maxSize;
};

export const checkFileType = (file, types = []) => {
    const type = getFileType(file?.name);
    return types.some(item => item.toUpperCase() === type?.toUpperCase());
};

export const checkFileLength = (file, maxLength = 1, fileList) => fileList.length <= maxLength;

export const buildInConfig = {
    max: {
        handler: checkFileSize,
        messageHandler: value => `文件大小不能超过${value}M`
    },
    type: {
        handler: checkFileType,
        messageHandler: value => `文件类型只能为${value.join(', ')}`
    },
    length: {
        handler: checkFileLength,
        messageHandler: value => `文件个数不能超过${value}个`
    }
};

export const getErrors = (rules = [], file, fileList) => {
    const error = [];
    rules.forEach(item => {
        const cfgType = Object.keys(buildInConfig).find(cfg => Object.keys(item).includes(cfg));
        if (cfgType) {
            const buildInCfg = buildInConfig[cfgType];
            const checkValue = item[cfgType];
            const { handler, messageHandler } = buildInCfg;
            if (!handler(file, checkValue, fileList)) {
                error.push(messageHandler(checkValue));
            }
        }

        const { validator, message } = item;
        if (validator && message) {
            if (!validator(file, fileList)) {
                error.push(message);
            }
        }
    });
    return error.length ? error.join(', ') : '';
};

// 简单处理tag显示的文件名
export const getFormatValue = (value = '') =>
    window.decodeURIComponent(value.replace(/\?.+/, '').slice(value.lastIndexOf('_') + 1) || value);

// 处理后端的数据转化为前端使用的对象
export const dataToFileList = (data, ossType = 'public') => {
    if (ossType === 'private') {
        if (!data) return [];
        // 后端约定的数据结构 [{keyName, originName, url}]
        return data.map(item => {
            const { keyName, originName, url } = item;
            return { uid: keyName, name: originName, url };
        });
    }

    let result = [];
    try {
        result = JSON.parse(data || '[]');
    } catch (error) {
        console.error(error);
    }
    return result;
};

export const fileListToData = (fileList, ossType = 'public') => {
    if (ossType === 'private') {
        if (!fileList) return [];

        // 这数据结构...
        return fileList.map(item => {
            const { uid, name, url } = item;
            return {
                keyName: uid,
                originName: name,
                url
            };
        });
    }

    return JSON.stringify(
        (fileList ?? []).map(item => {
            const { uid, name, response, url } = item; // 已存或者新上传的
            return {
                uid,
                name,
                url: url ?? response
            };
        })
    );
};

export const generateUploadResource = (uploadResource, categoryCode = '') => {
    if (!uploadResource.length) {
        return null;
    }
    return {
        categoryCode,
        keyNameAndOpt: uploadResource.map(item => {
            const { response, keyName, uid } = item; // 新上传，旧删除
            return `${item.action}:${response || keyName || uid}`;
        })
    };
};

/**
 * 获取 blob 需要支持跨域
 * @param  {String} url 目标文件地址
 * @return {cb}
 */
// function getBlob(url, cb, onError) {
//     const xhr = new XMLHttpRequest();
//     xhr.open('GET', url, true);
//     xhr.responseType = 'blob';
//     xhr.onload = () => {
//         if (xhr.status === 200) {
//             cb(xhr.response);
//         }
//     };
//     xhr.onerror = () => {
//         if (onError) onError();
//     };
//     xhr.send();
// }

/**
 * 保存
 * @param  {Blob} blob
 * @param  {String} filename 想要保存的文件名称
 */
// function saveAs(blob, filename) {
//     if (window.navigator.msSaveOrOpenBlob) {
//         navigator.msSaveBlob(blob, filename);
//     } else {
//         const link = document.createElement('a');
//         const body = document.querySelector('body');

//         link.href = window.URL.createObjectURL(blob);
//         link.download = filename;

//         // fix Firefox
//         link.style.display = 'none';
//         body.appendChild(link);

//         link.click();
//         body.removeChild(link);

//         window.URL.revokeObjectURL(link.href);
//     }
// }

/**
 * 下载
 * @param  {String} url 目标文件地址
 * @param  {String} filename 想要保存的文件名称
 */
export const download = (url, filename) => {
    FileSaver.saveAs(url, filename);
    // getBlob(
    //     url,
    //     blob => {
    //         saveAs(blob, filename);
    //     },
    //     // 无法下载时直接新页面打开
    //     () => {
    //         window.open(url);
    //     }
    // );
};

export const canPreview = fileName => PREVIEW_TYPE.includes(getFileType(fileName));
